package devbureau.fstore.common.db;

import devbureau.fstore.common.DeliveryInfo;
import devbureau.fstore.common.Item;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;


public class LoadDeliveryItemsDBTask<T extends DeliveryInfo> extends DBTask{

	List<Item> items = null;
    T deliveryInfo = null;

   	private static Logger logger = Logger.getLogger(LoadDeliveryItemsDBTask.class);

	public static final String NEXT_ITEM = "values nextval for STORE.ITEM_SEQ";
	public static final String INSERT_ITEM = "insert into STORE.ITEM(ID,DELIVERY_ID,SUPPLIER_LABEL,NAME,LENGTH,INCOMING_DATE,QUANTITY,PRICE,PRICE_RUR,BALANCE, PLANTATION) values (?,?,?,?,?,?,?,?,?,?,?)";
	
	public LoadDeliveryItemsDBTask(Connection connection,List<Item> items,T deliveryInfo) {
        super(connection);
		this.deliveryInfo = deliveryInfo;
        this.items = items;
	}


	public void run() throws Exception {
        logger.debug("#run enter");
        
        PreparedStatement ps =null;
        PreparedStatement psNextId =null;
        ResultSet rsNextId  = null;

		try{
			connection.setAutoCommit(false);

            Iterator<Item> iterator = items.iterator();
            while(iterator.hasNext()){
                Item item = iterator.next();
                logger.trace("#run item = " + item);
                psNextId = connection.prepareStatement(NEXT_ITEM);
                rsNextId  = psNextId.executeQuery();
                Integer itemNextId = null;
                if(rsNextId.next()){
                    itemNextId = rsNextId.getInt(1);
                }
                rsNextId.close();
                psNextId.close();
                logger.debug("INSERT ITEM(ID["+itemNextId+"],DELIVERY_ID["+deliveryInfo.getId()+"],SUPPLIER_LABEL["+item.getSupplierLabel()+"],NAME["+item.getName()+"]," +
                             "LENGTH["+item.getLength()+"],INCOMING_DATE["+item.getDeliveryDate()+"],QUANTITY["+item.getQuantity()+"],PRICE["+item.getPrice()+"],PRICE_RUR["+item.getPrice()*deliveryInfo.getRate()+"],BALANCE["+item.getQuantity()+"])");
                ps = connection.prepareStatement(INSERT_ITEM);

                ps.setInt(1, itemNextId);
                ps.setInt(2, deliveryInfo.getId());
                ps.setString(3,item.getSupplierLabel());
                ps.setString(4,item.getName());

                if(item.getLength() != null) {
                    ps.setInt(5,item.getLength());
                }else{
                    ps.setNull(5,Types.INTEGER);
                }
                
                if(item.getDeliveryDate() != null) {
                    ps.setDate(6,new java.sql.Date(item.getDeliveryDate().getTime()));
                }else{
                    ps.setNull(6,Types.DATE);
                }

                if(item.getQuantity() != null) {
                    ps.setInt(7,item.getQuantity());
                }else{
                    ps.setNull(7,Types.INTEGER);
                }

                if(item.getPrice() != null ) {
                    ps.setDouble(8,item.getPrice());
                    ps.setDouble(9,item.getPrice()*deliveryInfo.getRate());
                }else{
                    ps.setNull(8,Types.INTEGER);
                    ps.setNull(9,Types.INTEGER);
                }

                if(item.getQuantity() != null) {
                    ps.setInt(10,item.getQuantity());
                }else{
                    ps.setInt(10,new Integer(0));
                }
                ps.setString(11, item.getPlantation());

                ps.executeUpdate();
                ps.close();
            }

            ps.close();
			connection.commit();
		}catch(SQLException ex){
            logger.error("SQLException", ex);
			connection.rollback();
            throw new Exception("Не удалось загрузить в БД информацию об обновлении склада. Ошибка : " + ex.getMessage());
		}finally{
			connection.setAutoCommit(true);
		}
        logger.debug("#run exit");
	}
}
